<template>
  <!-- 待派工 -->
  <el-main class="vertical">
    <el-container style="height:55%;">
      <basic-crud ref="topCrudRrf" :option="option" apiGetListUrl="mes/specificationTaskController/listUnDispatchTask"
                  apiGetListMethod="post" class="curdTop" selectType="multiple"
                  :fastSearch="{name:'计划编号、项目号、产品型号、产品编号、产品名称',fastColumn:'sourceCode,workOrderCode,modelName,pdmProductCode,pdmProductName'}"
                  :defaultListParams="orderParams" @row-click="handleRowClick">
        <template #firstArticleFlag="{ row }">
          <el-tag v-if="row.firstArticleFlag === 'true'" type="danger">首件</el-tag>
        </template>
        <template #menu="{row}">
          <el-button  icon="circle-plus" text type="primary" :loading="singleLoading"
                      v-permission="'treatDispatching-SINGLEDISPATCH'" @click="handleSingleDispatching(row)">派工</el-button>
          <el-badge :value="row.problemFeedbackCount" class="techne-badge-treat item">
            <el-button  icon="sugar" text type="primary" v-permission="'treatDispatching-ADDPROBLEMINSEPC-ADDPROBLEMINSEPC'"
                        @click="onOpenFeedback(row)">填写问题反馈单</el-button>
          </el-badge>
        </template>
        <template #menu-left>
          <el-button
              type="primary"
              icon="circle-plus"
              :loading="batchLoading"
              v-permission="'treatDispatching-BATCHDISPATCH'"
              @click="onOpenBatchDispatching()"
          >批量派工</el-button>
        </template>
      </basic-crud>
    </el-container>

    <!-- 工序详情页面组件 -->
    <techne-deails style="height:45%" ref="technoDeailsRef" :hidden-btn="true" :hidden-form="true"
                   :must-show-menu="true" :autoLoad="false"></techne-deails>
    <!--方案-->
    <person-tem-list ref="personTemListRef" @refresh-parent="handleRefresh"></person-tem-list>
    <!--问题反馈单-->
    <feedback ref="feedbackFormsRefs" @refresh-parent="handleRefresh"></feedback>
  </el-main>
</template>

<script setup>
import {ref} from "vue";
import TechneDeails from "@/views/mes/techne/TechneDeails.vue";
import PersonTemList from "@/views/generate/treatDispatching/personTemList.vue";
import Feedback from "@/views/mes/techne/feedback.vue";
import { formatDate } from "@/utils/formatTime";
import {
  postTaskList,
  cancelDispatch,
  getSchemaList,
  getMaterial,
  checkOnlyOneSchema,
  changeUser,
  listTask, singleDispatchTask, batchDispatchTask,
} from "@/apis/generate/treatDispatching";

const bottomHeight = ref((document.body.clientHeight - 120) * 0.45 - 75);//0.45是父容器的高度设为45%

const option = ref({
  highlightCurrentRow: true,
  calcHeight: bottomHeight.value + 90,
  multiple: true,
  addBtn: false,
  editBtn: false,
  delBtn: false,
  menuWidth: 240,
  column: [
    {
      label: "计划编号",
      prop: "sourceCode",
      minWidth: 220,
      search:true
    },
    {
      label: "项目号",
      prop: "workOrderCode",
      sortable: true,
      minWidth: 150,
      search: true,
      searchSpan:6,
    },
    {
      label: "产品型号",
      prop: "modelName",
      sortable: true,
      minWidth: 150,
      search: true,
      searchSpan:6,
    },
    {
      label: "产品编号",
      prop: "pdmProductCode",
      sortable: true,
      minWidth: 150,
      search: false,
    },
    {
      label: "产品名称",
      prop: "pdmProductName",
      sortable: true,
      minWidth: 150,
    },
    {
      label: "首件标识",
      prop: "firstArticleFlag",
      width: 150,
      slot: true,
    },
    {
      label: "规程编号",
      prop: "code",
      sortable: true,
      minWidth: 150,
      searchSpan:6,
      search: true,
    },

    {
      label: "规程名称",
      prop: "name",
      overHidden: true,
      sortable:true,
      width: 150,
    },
    {
      label: "版本",
      prop: "specificationRev",
      sortable: true,
      overHidden: true,
      width: 70,
    },
    {
      label: "产品主管",
      prop: "assignerName",
      hide:true,
      minWidth: 80,
    },
    {
      label: "计划开始日期",
      prop: "needStartDate",
      sortable: true,
      width: 120,
      formatter: (row) => {
        return formatDate(row.needStartDate, "yyyy-MM-dd");
      },
    },
    {
      label: "计划结束日期",
      prop: "needEndDate",
      sortable: true,
      width: 120,
      formatter: (row) => {
        return formatDate(row.needEndDate, "yyyy-MM-dd");
      },
    },{
      label:'关重件',
      prop: 'importantSign',
      display: false,
      width: 80,
      sortable: true,
      type: 'select',
      search: true,
      searchType: 'select',
      dicData: [{
        label:'关键件',
        value: '1'
      },{
        label: '重要件',
        value: '2'
      },{
        label: '普通件',
        value: '3'
      }]
    },{
      label:'数量',
      prop: 'quantity',
      width:70,
    },{
      label:'批次号',
      prop: 'batchNum',
      width: 180,
      overHidden: true
    },{
      label: '配套机型',
      prop: 'applyProduct',
      width: 130
    },
    {
      label: "紧急程度",
      prop: "exigencyLevel",
      display: false,
      width: 90,
      type: "select",
      dicData: [
        {
          label: "不紧急",
          value: "none",
        },
        {
          label: "一般",
          value: "normal",
        },
        {
          label: "紧急",
          value: "exigency",
        },
        {
          label: "非常紧急",
          value: "veryExigency",
        },
      ],
      formatter: (val) => {
        return val.exigencyLevelText;
      },
    },
    {
      label: "军检",
      prop: "armyCheck",
      display: false,
      width: 70,
      type: "switch",
      dicData: [{
        label: '否',
        value: 'false'
      },{
        label: '是',
        value:'true'
      }]
    }
  ]
});

//排序参数
const orderParams=ref({
  orderList: [{ orderBy: "createTime", orderMethod: "desc" }]
})

const technoDeailsRef=ref(null)
const handleRowClick=(row) =>{
  technoDeailsRef.value?.loadOnlyBySpecTask(row, 'worker');
}

const topCrudRrf=ref(null);
const personTemListRef=ref(null)
//批量派工
const batchLoading=ref(false);
const onOpenBatchDispatching=()=> {
  if (topCrudRrf.value.selectData.length <= 0) {
    return ElMessage.warning('至少选择一条数据！')
  }

  if (topCrudRrf.value.selectData.some(row => row.problemFeedbackCount !== 0)) {
    return ElMessage.error('所选行中存在未处理的问题反馈，无法执行派工操作');
  }

  let taskIds = topCrudRrf.value.selectData.map((items) => {
    return items.id;
  });

  if (topCrudRrf.value.selectData.find((val) => (!val.assigner || val.assigner == null || val.assigner == ''))) {
    return ElMessage.error("任务必须先添加产品主管才能派工");
  }
  ElMessageBox.confirm(`批量派工时是否应用人员模板方案?`, "提示", {
    confirmButtonText: "是",
    cancelButtonText: "否",
    distinguishCancelAndClose: true,
    type: "warning",
  })
      .then(() => {
        let codeStatus = topCrudRrf.value.selectData.every(item => {
          return item.specificationId === topCrudRrf.value.selectData[0].specificationId;
        });
        if (!codeStatus) {
          //如果存在规程数据，说明这些规程不存在或存在多个方案
          let codeArr = topCrudRrf.value.selectData.map((item) => {
            return item.code;
          });
          ElMessage.error(codeArr.join(",") + "等规程不存在人员模板或存在多个人员模板，请单独派工处理！"
          );
        } else {
          //批量派工，应用人员模板
          checkOnlyOneSchema({ids: taskIds}, batchLoading)
              .then((res) => {
                if (res.success) {
                  /// 我们只需要显示人员模版即可
                  batchDispatchTask({useTemplate: true, ids: taskIds}, batchLoading)
                      .then((res) => {
                        if (res.success) {
                          ElMessage.success(res.msg || "派工成功！");
                          topCrudRrf.value.getList();
                        } else {
                          ElMessage.error(res.msg);
                        }
                      })
                      .catch(() => ElMessage.error("派工失败！"));
                } else {
                  personTemListRef.value.openDialog(topCrudRrf.value.selectData[0], taskIds, true);
                }
              })
              .catch(() => {
                ElMessage.error("批量派工失败！");
              });
        }
      })
      .catch((action) => {
        //批量派工，不应用人员模板。
        if (action === 'close') {
          return ElMessage.info('已取消!');
        }
        batchDispatchTask({useTemplate: false, ids: taskIds}, batchLoading)
            .then((res) => {
              if (res.success) {
                ElMessage.success(res.msg || "派工成功！");
                topCrudRrf.value.getList();
              } else {
                ElMessage.error(res.msg);
              }
            })
            .catch((error) => {ElMessage.error("派工失败！")});
      });
}

//派工
const singleLoading=ref(false);
const handleSingleDispatching=(row)=>{
  if (row.problemFeedbackCount > 0) {
    return ElMessage.error('问题反馈单未处理，需要进行处理');
  }
  if (!row.assigner || row.assigner == '') {
    return ElMessage.error('没有设置产品主管，不能执行');
  }
  ElMessageBox.confirm(`派工时是否应用人员模板方案?`, "提示", {
    confirmButtonText: "是",
    cancelButtonText: "否",
    distinguishCancelAndClose: true,
    type: "warning",
  })
      .then(() => {
        //单个派工，应用人员模板方案
        let params = {specificationId: row.specificationId};
        getSchemaList(params,singleLoading)
            .then((res) => {
              if (res.success) {
                if (res.data.length > 0) {
                  personTemListRef.value.openDialog(row);
                } else {
                  ElMessage.error("【" + row.code + " " + row.name +
                      "】该规程没有人员模板方案可以使用，请先添加人员模板方案！");
                }
              } else {
                ElMessage.error(res.msg);
              }
            })
            .catch(() => {
              ElMessage.error("派工失败！");
            });
      })
      .catch((action) => {
        if (action === 'close') {
          return ElMessage.info('已取消!');
        }
        let taskIds = [row.id];
        const params = {
          ids: taskIds,
          useTemplate: false
        };
        singleDispatchTask(params,singleLoading)
            .then((res) => {
              if (res.success) {
                ElMessage.success(res.obj || "派工成功！");
                topCrudRrf.value.getList();
              } else {
                ElMessage.error(res.msg);
              }
            })
            .catch((error) => {ElMessage.error("派工失败！")});
      });
}

//填写问题反馈单
const feedbackFormsRefs=ref(null);
const onOpenFeedback=(row)=>{
  feedbackFormsRefs.value.openDialog(row, false, true);
}

const handleRefresh=()=>{
  topCrudRrf.value.getList();
}
</script>

<style lang="scss" scoped>
::v-deep {
  .item .el-badge__content {
    margin-top: 8px;
    margin-right: 2px;
    height: 16px;
    border-radius: 7px;
    font-size: 12px;
    line-height: 14px;
    padding: 0 4px;
  }
}
</style>